想預測每日股價,利用證交所網址,來抓出所需的天數吧
import requests
from io import StringIO
import pandas as pd
import numpy as np
from logging import exception
import datetime
from chinese_calendar import is_workday
from dateutil.relativedelta import relativedelta
抓最近兩個月(近六十天)的收盤價
df_2330_2m = pd.DataFrame({'證券代號':[], '證券名稱':[], '成交股數':[], '成交筆數':[], '成交金額':[], '開盤價':[], '最高價':[], '最低價':[], '收盤價':[]})
for i in range(0,60,1):
date = datetime.datetime.now().date()+relativedelta(days=-i)
if is_workday(date):
datestr = date.strftime('%Y%m%d')
print(datestr)
#datestr = '20220926'
# 下載股價
r = requests.post('https://www.twse.com.tw/exchangeReport/MI_INDEX?response=csv&date=' + datestr + '&type=ALL')
try:
# 整理資料,變成表格
df = pd.read_csv(StringIO(r.text.replace("=", "")),
header=["證券代號" in l for l in r.text.split("\n")].index(True)-1,converters={'證券代號':str},encoding='utf-8')
# 整理一些字串:
df = df.apply(lambda s: pd.to_numeric(s.astype(str).str.replace(",", "").replace("+", "1").replace("-", "-1"), errors='coerce'))
df_2330 = df[['證券代號', '證券名稱', '成交股數', '成交筆數', '成交金額', '開盤價', '最高價', '最低價', '收盤價']][df['證券代號']==2330]
df_2330_2m = df_2330_2m.append(df_2330)
except:
pass
print("是休息日")
else:
print("是休息日")